import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import { Table, Menu, Popconfirm, message } from 'antd';


import userActions from '../action'
import appActions from '../../app/action'

import UserForm from './UserForm';

import {dateToString} from '../../../util/index';

export class Users extends Component {

  state = {
    index : null,
    formType : 'add',
    formValues : null,
    formVisible : false
  }

  constructor (props) {
    super(props);

    /**
     * table头部
     * @type {*[]}
     */
    this.columns = [{
      title: '昵称',
      width: 150,
      dataIndex: 'user_nickname',
      key: 'nickname',
    }, {
      title: '邮箱',
      width: 150,
      dataIndex: 'user_email',
      key: 'email',
    },{
      title: '注册时间',
      width: 200,
      dataIndex: 'user_registered',
      key: 'register',
      render : (text) => {
        return dateToString(text);
      }
    }, {
      title: '状态',
      dataIndex: 'user_status',
      key: 'status',
      render: (text, record) => {
        let span = {
            text: '正常',
            color: '#093'
          };

        if (text == -1) {
          span.text = '冻结';
          span.color = '#ff0000';
        }

        return <span style={{color: span.color}}>{span.text}</span>;
      }
    }, {
      title: '权限',
      dataIndex: 'user_role',
      key: 'role',
      render: (text, record) => {
        switch (text){
          case '0':
            return '管理员';
          default:
            return '一般用户';
        }
      }
    }, {
      title : '操作',
      render: (text,record,index) => {
        const statusText = record.user_status === 0 ? '冻结' : '解冻',
          statusTextTip = "确定"+statusText+"此账号么?";
        return (
          <span>
            <a href="JavaScript:;" onClick={this.handleUserEdit.bind(this,record,index)}>编辑</a>
            <span className="ant-divider" />
            <Popconfirm title={statusTextTip} onConfirm={this.handleUserFroze.bind(this,record,index)} >
              <a href="#">{statusText}</a>
            </Popconfirm>
            <span className="ant-divider" />

            <Popconfirm title="确定删除此账号么?" onConfirm={this.handleUserDelete.bind(this,record,index)} >
              <a href="#">删除</a>
            </Popconfirm>
          </span>
        )
      },
    }];
  }

  componentDidMount () {
    this.getUserList(1);
  }

  /**
   * 根据page获取用户列表
   * @param page
   */
  getUserList (page) {
    const { appActions, userActions } =  this.props;
    appActions.loading(true).then(()=>{
      return userActions.getList({page})
    }).then(()=>{
      appActions.loading(false)
    }).catch(err=>{
      message.error(err.msg);
    })
  }

  /**
   * 菜单点击操作
   * @param e
   */
  handleMenuClick (e) {
    if(e.key === 'add'){
      this.setState({
        formType : 'add',
        formValues : null,
        formVisible : true
      })
    }
  }

  /**
   * 隐藏modal弹出层
   */
  handleHideModal () {
    this.setState({
      formValues : null,
      formVisible:false
    })
  }
  
  handleUserSubmit (formdata) {
    const {userActions} = this.props;
    if(formdata._id){
      formdata.index = this.state.index;
      userActions.postEditUser(formdata).then(data=>{
        this.handleHideModal();
      }).catch(err=>{
        typeof err.msg == 'object' ?
          message.error(err.msg.message) :
          message.error(err.msg);
      });
    }else{
      userActions.postAddUser(formdata).then(data=>{
        this.handleHideModal();
      }).catch(err=>{
        message.error(err.msg);
      });
    }
  }

  handleUserEdit (formValues,index) {
    this.setState({
      index,
      formType : 'edit',
      formVisible:true,
      formValues
    })
  }

  /**
   * 操作冻结/解冻用户
   * @param _id
   */
  handleUserFroze (formdata,index) {
    this.props.userActions.postFrozeUser({
      index,
      _id : formdata._id,
      user_status : formdata.user_status == -1 ? 0 : -1
    }).then(data=>{
      let text = formdata.user_status == -1 ? '解冻' : '冻结';
      message.success(text+'成功');
    }).catch(err=>{
      message.error(err.msg);
    })
  }
  

  /**
   * 操作删除用户
   * @param _id
   */
  handleUserDelete (formdata,index) {
    this.props.userActions.postDeleteUser({
      index,
      _id : formdata._id,
    }).then(data=>{
      message.success('删除成功');
    }).catch(err=>{
      message.error(err.msg);
    })
  }

  /**
   * 分页改变
   * @param page
   */
  handleTableChange (pagination) {
    this.getUserList(pagination.current);
  }


  render() {

    const {user} = this.props;
    const list = user.get('userlist') && user.get('userlist').toArray();
    const pagination = user.get('pagination') && user.get('pagination').toJS();

    return (
      <div>
        <Menu onClick={this.handleMenuClick.bind(this)}
              selectedKeys={['list']}
              mode="horizontal">
          <Menu.Item key="list">
            用户列表
          </Menu.Item>
          <Menu.Item key="add" style={{marginLeft: 20}}>
            添加用户
          </Menu.Item>
        </Menu>

        <Table
          bordered
          columns={this.columns}
          dataSource={list}
          className="mt20"
          pagination={pagination}
          onChange={this.handleTableChange.bind(this)}
        />

        <UserForm
          formType={this.state.formType}
          formValues={this.state.formValues}
          formVisible={this.state.formVisible}
          handleHide={this.handleHideModal.bind(this)}
          handleOK={this.handleUserSubmit.bind(this)}
        />
      </div>
    )
  }

}

export default connect((state)=>{
  return  {
    user : state.get('user')
  }
},dispatch => {
  return {
    userActions : bindActionCreators(userActions, dispatch),
    appActions : bindActionCreators(appActions, dispatch)
  }
})(Users);
